package collect

import (
	"bufio"
	"log"
	"os"
	"os/exec"

	"fish-scaner/adl"
	"fish-scaner/zip"

	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/glog"
	"github.com/gogf/gf/text/gregex"
)

func Collect(workDir, fishdb, collectMod, willZipDirName string, ws *ghttp.WebSocket, stdErrCh chan error) { // pyErrcod int, err error

	//
	// run := exec.Command(`python3`, `/root/object/rzh/`+fishdb+`_`+systematics+`.py`, willZipDirName)
	// stdOut = new(string)
	command := workDir + `rzh/` + fishdb + `_` + collectMod + `.py`
	// stdOutBuffer := new(bytes.Buffer)
	// cmd := stdOutBuffer.ReadByte
	// log.Fatalln(command)
	// ws.SentWithFlag(`stdOut`, `开始爬取`)
	if err := ws.WriteMessage(1, adl.SentWithFlag(`stdOut`, `开始爬取`)); err != nil {
		glog.Println(`ws sent err:`, err, `!`)
	}
	cmd := exec.Command(`python3`, command, willZipDirName)
	// command := `python3 ` + workDir + fishdb + `_` + collectMod + `.py` + ` ` + willZipDirName
	// *stdOut, err = gproc.ShellExec(command)
	// os.Stdout = *stdOut
	// cmd.Stdout = stdOutBuffer.cmd
	// stdOutBuf := bufio.NewWriter(cmd.Stdout)
	stdOutBuf := bufio.NewReader(os.Stdout)
	// new(bufio.Writer)

	// stdOutBuf.Reset(cmd.Stdout)
	// (cmd.Stdout)
	// byteReader:=bytes.NewReader()
	// byteReader:=bufio.NewReader(cmd.Stdout)
	go func() {
		for i := 0; ; i++ {
			if i > 100 {
				break
			}
			s := make([]byte, 100)
			_, err := stdOutBuf.Read(s)
			if err != nil {
				log.Fatalln(`buf err:`, err, command)
			}
			// log.Println(`bufio out:`, string(s))

		}
	}()
	stdOut, err := cmd.Output()
	// cmd.Stderr = os.Stderr
	// *stdOut, err = gproc.ShellExec(`python3 /root/object/rzh/` + `fishdb_shu.py` + ` ` + `Chirocentrus dorab`)

	// stdOut = []byte(os.Stdout.Sync().Error())
	// stdOut = stdOutBuffer.Bytes()
	// log.Println(`collect out:`, string(stdOut))
	// stdOut, err = cmd.Output()
	// if err != nil {
	// log.Println(`Output err:`, err, command)
	// ch <- true
	// return nil, 0, err
	// }

	// err = cmd.Run()
	// log.Println(string(stdOut))
	if err != nil {

		// stdOutMap := make(map[string]interface{})
		// stdOutMap[`pyErrCode`] = 0
		// stdOutMap[`stdOut`] = command
		stdOutMap := map[string]interface{}{
			`pyErrCode`: 0,
			`stdOut`:	 command,
		}
		// ws.SentWithFlag(`pyErr`, stdOutMap)
		if err := ws.WriteMessage(1, adl.SentWithFlag(`pyErr`, stdOutMap)); err != nil {
			glog.Println(`ws sent err:`, err, `!`)
		}
		// go func() { stdOutMapCh <- stdOutMap }()
		stdErrCh <- err
		log.Fatalln(`Run err:`, err, command, willZipDirName)
		// stdOutMapCh <- stdOutMap
		// return 0, err
		return
	}

	zip.ScanDir(workDir+`tmp_files/`+fishdb+`/`+collectMod, willZipDirName, true, ws)

	// log.Println(`--------------------------------`)
	analysisCollectOutput(string(stdOut), ws, stdErrCh)

}

// func analysisCollectOutput(stdOut string, stdOutMapCh chan map[string]interface{}, stdErrCh chan error) { // pyErrcode int, err error
func analysisCollectOutput(stdOut string, ws *ghttp.WebSocket, stdErrCh chan error) { // pyErrcode int, err error

	// ws.SentWithFlag(`stdOut`, stdOut)

	if err := ws.WriteMessage(1, adl.SentWithFlag(`stdOut`, stdOut)); err != nil {
		glog.Println(`ws sent err:`, err, `!`)
	}
	pyOut := string(stdOut)
	// fmt.Println(pyOut)
	//
	match, _ := gregex.MatchAllString(`\{.*}`, pyOut)

	stdOutMap := map[string]interface{}{
		// `stdOut`: stdOut,
	}
	for _, line := range match {
		for _, jsonStr := range line {
			j := gjson.New(jsonStr)
			stdOutMap[`pyErrCode`] = j.GetInt("sign")
			switch stdOutMap[`pyErrCode`] {

			case 40163:
				//爬取中出现错误
				log.Println(`collect err2:`, `collect fail with python bug`)
				// stdOutMap := map[string]interface{}{
				// `pyErrCode`: pyErrcode,
				// `stdOut`:	 stdOut,
				// }
				// ws.SentWithFlag(`collectOutPut`, stdOutMap)
				if err := ws.WriteMessage(1, adl.SentWithFlag(`stdOut`, `爬取中出现错误`)); err != nil {
					glog.Println(`ws sent err:`, err, `!`)
				}
				stdErrCh <- nil
				// stdOutMapCh <- stdOutMap
				return
				// return pyErrcode, errors.New(`collect fail with python bug`)

			case 1:
				// stdOutMap[`pyErrCode`] = pyErrcode
				// ws.SentWithFlag(`collectOutPut`, stdOutMap)
				// ws.SentWithFlag(`stdOut`, `该图片库有更新`)
				if err := ws.WriteMessage(1, adl.SentWithFlag(`stdOut`, `该图片库有更新`)); err != nil {
					glog.Println(`ws sent err:`, err, `!`)
				}
				stdErrCh <- nil
				// stdOutMapCh <- stdOutMap
				return
				//该图片库有更新
				// log.Println(`img has update`)
				// return pyErrcode, errors.New(`img has update`)
			}
		}
	}

	// go  stdOutCh <- string(stdOut)
	// go func() { stdOutCh <- stdOut }()
	// return pyErrcode, nil
}
